<template>
	<view>
		<x-loading></x-loading>
			<swiper v-if="goods.goodsRotator" :indicator-dots="goods.goodsRotator.length>1 ? true : false" style="height: 750rpx;">
				<swiper-item v-for="(item, index) in goods.goodsRotator" :key="index">
					<view class="banner_img" @click="previewImg(index)">
						<image mode="heightFix" :src="imageUrl+item"></image>
					</view>
				</swiper-item>
			</swiper>

		<view class="padding_box">
			<view class="goods_content" v-if="goods.name">
				<view class="goods_price">
					<price :value="goods.goodsPriceCurrent" />
				</view>

				<view class="goods_title">
					<text>{{ goods.name }}</text>
					<button open-type="share" class="btn_share"><u-icon size="24" name="share"></u-icon></button>
				</view>
			</view>
		</view>

		<u-divider v-if="goods.goodsIntroduce" text="商品介绍" lineColor="#515151"
			customStyle="width:250rpx;margin:20rpx auto;"></u-divider>
		<view class="introduce">
			
			<u-parse :content="goods.goodsIntroduce"></u-parse>
		</view>
		
		<!-- 底部按钮 -->
		<view class="footer"
			:style="{height:(bottomHeight+device.customBottomHeight)+'px', 'padding-bottom':device.customBottomHeight+'px'}">
			<!-- <x-footer> -->
			<view open-type="contact" class="btn_car">

				<u-button :customStyle="{'border': 'none', 'height': '28px;'}" icon="server-fill" :hair-line='false'
					open-type="contact" iconColor="#2D2D2D">
				</u-button>
				<button hover-class="none" :show-message-card="true" open-type="contact"
					style="height: 40rpx;vertical-align:top;font-size: 11px;">客服</button>
			</view>
			<!-- <navigator url="/pages/index?" open-type="reLaunch" hover-class="none" class="btn_car">
				<u-icon name="shopping-cart" size="28"></u-icon>
				<button style="height: 40rpx;vertical-align:top;font-size: 11px;">购物车</button>
				<u-badge :offset="[0,'20%']" max="10" absolute="true" :value="carGoodsNum"></u-badge>
			</navigator> -->
			<button class="btn_add_car" @click="showAlert = true; alertType = 0;">
				加入购物车
			</button>
			<button class="btn_buy x-btn" @click="checkLogin">
				立即下单
			</button>
		</view>

		<!-- 购买弹框 -->
		<block>
			<u-popup :show="showAlert" mode="bottom" @close="showAlert = false" @open="onOpen">
				<view class="alert">
					<view class="alert_title">
						<view class="goods_info">
							<view class="goods_img">
								<x-image :src="imageUrl+goods.skuList[currentSku].picturePath"></x-image>
							</view>
							<!-- <view class="goods_price">￥{{ goods.goodsPrice }}</view> -->
							<view class="desc">
								<price :value="goods.skuList[currentSku].goodsPriceCurrent" />
								<span class="unit" v-if="goods.unit && goods.unit.length>0">单位：{{goods.unit}}</span>
							</view>

						</view>
						
						<view class="alert_right">
							<image src="../../static/icon/ic_close.png" @click="showAlert = false" class="ic_close">
							</image>
							<u-number-box :min="1" :max="goods.skuList[currentSku].quantity" button-size="28" ref="goodsNum"
								v-model="goodsNum"></u-number-box>
						</view>
					</view>
					
					<view class="sku">
						<view
							class="sku_btn"
							:style="{borderColor:currentSku == index?'red':'',color:i.quantity>0?'':'#999'}"
							@click="currentSku = index;goodsNum = 1"
							v-for="(i,index) in goods.skuList" 
							:key="i.id">
							{{i.name}}
						</view>
					</view>
					
					<template v-if="goods.skuList[currentSku].quantity>0">
						<button class="btn_sub x-btn" v-if="alertType" @click="toOrder">提交订单</button>
						<button class="btn_sub x-btn" v-else @click="onAddCar">加入购物车</button>
					</template>
					<template v-else>
						<button class="btn_sub x-btn">已售罄</button>
					</template>
					
				</view>
			</u-popup>
		</block>
	</view>
</template>

<script>
	import config from '@/config';
	import {
		getGoodsById
	} from '@/api/goods.js';
	
	import {
		subOrder
	} from '@/api/order.js';
	import {
		getShop
	} from '@/api/shop.js'
	import {
		mapState
	} from 'vuex'

	import EventBusMacro from '@/plugins/EventBus/eventBusMacro.js'

	import XGoodsDetail from './components/xGoodsDetail.vue'
	import XImage from '@/components/image/xImage.vue'
	
	export default {
		computed: {
			...mapState(['userInfo', 'device'])
		},
		components: {
			XGoodsDetail,
			XImage,
		},
		data() {
			return {
				// showDetail: false,
				imageUrl: config.imageUrl,
				currentSku:0,
				showAlert: false,
				alertType: 0,
				id: '',
				goods: {},
				// 购买数量
				goodsNum: 1,
				shopList: [],
				shopName: '',
				bottomHeight: 50, // 以像素为单位
				carGoodsNum: 0,
				token: '',
				firstOrderGift: {}
			};
		},

		onLoad(options) {
			wx.getVideoInfo({
				src:'http://192.168.1.22:8099/cfaf2530-984e-46fc-937a-6fd758b39288.mp4',
				complete:c=>{
					console.log('video',c)
				}
			})
			this.$events.on(EventBusMacro.EB_LOGIN_SCUCCESS, this.onLoginSuccess);

			this.carGoodsNum = uni.getStorageSync('car').length
			this.token = uni.getStorageSync('token')
			if (options.key === this.$TOOLS.SHARE.SHARE_STYLE.PAGE) {
				let {
					params,
					target
				} = this.$TOOLS.SHARE.decodeShareParameter(this.$TOOLS.SHARE.SHARE_STYLE.PAGE, options)
				console.log("onLoad params=", params, ",target=", target)
				if (target == this.$TOOLS.SHARE.TARGET_MYSELF) {
					this.id = params.id
					let invitationCode = params.invitationCode || ''
					let myInvitationCode = this.userInfo.invitationCode || ''
					console.log(invitationCode, myInvitationCode);
					if (myInvitationCode != invitationCode && invitationCode != '') {
						this.$store.commit('SET_INVITATION_CODE', invitationCode);
					}
				}
			} else {
				this.id = options.id
			}
			this.loadData()
		},

		onBeforeDestroy() {
			this.$events.off(EventBusMacro.EB_LOGIN_SCUCCESS, this.onLoginSuccess);
		},
		methods: {
			onOpen() {},
			onLoginSuccess() {
				this.loadData()
			},
			loadData() {
				this.$showLoading();
				getGoodsById(this.id).then(res => {
					console.log('22222')
						this.goods = res;
						var a = res.goodsIntroduce;
						a = a.replace(/iframe/gi,'video');
						a = a.replace(/src="\/images/gi,'src="'+this.imageUrl)
						this.goods.goodsIntroduce = a
						// this.goods.goodsIntroduce = this.formatRichText(a)
						console.log('goods',this.goods.goodsIntroduce)
						uni.setStorageSync('goods', this.goods);
						this.$hideLoading();
				
					})
					.catch(error => {
						this.$hideLoading();
					});
			},
			
			formatRichText(html){
			  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
			    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			    return match;
			  });
			  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
			    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
			    return match;
			  });
			  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
			  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
			  return newContent;
			},

			checkLogin(e) {
				// const token = uni.getStorageSync('token');
				if (!this.userInfo) {
					uni.navigateTo({
						url: "/pages/login/index"
					})
				} else {
					this.showAlert = true;
					this.alertType = 1;
				}
			},
			shareGoods() {
				uni.showShareMenu({
					menus: ['shareAppMessage', 'shareTimeline'],
					complete: res => {
						console.log(res);
					}
				});
			},
			// getFirst() {
			// 	getFirst().then(res => {
			// 		this.firstOrderGift = res;
			// 	})
			// },
			// 查看图片
			previewImg(i) {
				const imgList = new Array();
				this.goods.goodsRotator.forEach(url=>{
					imgList.push(this.imageUrl+url)
				})
				uni.previewImage({
					urls: imgList,
					current: i
				});
			},
			toOrder() {
				const info = new Object();
				
				info.goodsNormsId = this.goods.skuList[this.currentSku].id;
				info.quantity = this.goodsNum;
				info.price = this.goods.skuList[this.currentSku].goodsPriceCurrent;
				info.unit = this.goods.unit;
				
				const order = new Object()
				order.orderDetailEntityList = new Array();
				order.orderDetailEntityList.push(info);
				subOrder(order).then(res => {
					uni.navigateTo({
						url: `subOrder?id=${res.id}`,
						success: () => {
							this.showAlert = false;
						}
					});
				});
			},
			// 添加购物车
			onAddCar() {
				
				// const token = uni.getStorageSync('token');
				// if (!token) {
				// 	// this.showLogin = true;
				// 	// return false;
				// 	uni.navigateTo({
				// 		url: "/pages/login/index"
				// 	})
				// 	return;
				// }
				var car = uni.getStorageSync('car') || new Array();
				const info = new Object();
				const sku = this.goods.skuList[this.currentSku]
				info.picturePath = sku.picturePath;
				info.goodsName = this.goods.name+" ["+sku.name+"]";
				info.quantity = this.goodsNum;
				info.price = sku.goodsPriceCurrent;
				
				info.goodsNormsId = sku.id;
				info.unit = this.goods.unit;
				var isNew = true;
				for (var i = 0; i < car.length; i++) {
					if (car[i].goodsNormsId == info.goodsNormsId) {
						car[i].quantity += info.quantity;
						isNew = false;
						break;
					}
				}
				if (isNew) {
					car.unshift(info);
				}
				uni.setStorageSync('car', car);
				this.carGoodsNum = uni.getStorageSync('car').length
				this.showAlert = false;
				uni.showToast({
					icon: 'none',
					title: '已加入购物车'
				});
			},
			// 选择规格
			selectSpecifications(e, index) {
				for (var i = 0; i < this.specificationsList.length; i++) {
					this.specificationsList[i].checked = false;
				}
				this.specificationsList[index].checked = !e.checked;
			},
			selectShop(e) {
				this.shopName = this.shopList[e.detail.value].name;
				this.goods.shopId = this.shopList[e.detail.value].id;
			},

			_share(type) {

				let encodeParameter = this.$TOOLS.SHARE.encodeShareParameter(this.$TOOLS.SHARE.SHARE_STYLE.PAGE, this
					.$TOOLS.SHARE.TARGET_MYSELF, {
						id: this.goods.id,
						invitationCode: this.userInfo.invitationCode
					})
				console.log("_share encodeParameter=", encodeParameter)
				if (type == 0) {
					return {
						title: this.goods.name,
						path: `/pages/index/detail?` + encodeParameter,
					};
				} else if (type == 1) {
					if (this.goods.goodsRotator?.length > 0 ) {
						return {
							title: this.goods.name,
							path: `/pages/index/detail?` + encodeParameter,
							imageUrl: this.goods.goodsRotator[0]
						}
					} else {
						return {
							title: this.goods.name,
							path: `/pages/index/detail?` + encodeParameter,
						}
					}
				} else {
					// do nothing
				}

			},
		},

		onShareAppMessage() {
			return this._share(0)
		},
		onShareTimeline() {
			return this._share(1)
		},
	};
</script>


<style>
	.introduce video{
		width: 100%;
	}
</style>
<style lang="scss" scoped>
	@import "@/mixins/theme/xTheme.scss";

	.btn_share {
		border: none;
		display: block;
	}
	.mask {
		width: 100%;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.7);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 1;
		display: flex;
	}
	.text_red {
		color: #f56c6c;
	}

	.banner_img {
		width: 100%;
		height: 100%;
		margin: 0 auto;
		display: flex;
		justify-content: center;
		overflow: hidden;
		position: relative;
		
		&>image{
			height: 100%;
			margin: 0 auto;
		}
	}
	.goods_img {
		width: 100%;
	}

	.padding_box {
		padding: 30rpx 0 10rpx;
		border-bottom: 10rpx solid #f0f0f0;
	}

	.goods_content {
		width: 710rpx;
		margin: 0 auto;
		.goods_price {
			display: flex;

			.x-estimate-price {
				margin-left: 10rpx;
			}
		}

		.goods_title {
			line-height: 50rpx;
			display: flex;
			justify-content: space-between;
			color: #2c2c2c;
			font-weight: bold;
			padding: 10rpx 0px;
			align-items: center;
			
			&>text{
				width: 650rpx;
			}
		}

		.goods_info {
			font-size: 26rpx;
			display: flex;
			justify-content: space-between;
			color: #8a8a8a;
			padding: 30rpx 30rpx 10rpx;
		}
	}

	.goods_introduce {
		&>image {
			width: 100%;
		}

		.desc {
			font-family: 'PingFang SC';
			font-size: 12px;
			font-weight: normal;
			color: #6A6A6A;
		}
	}

	.buyer {
		background-color: rgba(245, 108, 108, 0.2);
		border: 2rpx solid #8a8a8a;
		margin: 10rpx auto;
		width: 100%;
		color: #f56c6c;
		font-size: 28rpx;
		padding: 20rpx;

		.buyer_item {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;

		}
	}

	.footer {
		width: 100%;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		border-top: 1px solid #F5F5F5;

		.btn_car {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 18%;
			position: relative;
		}

		.btn_add_car {
			width: 30%;
			display: flex;
			background-color: #ff9800;
			color: #fff;
			align-items: center;
			height: 100%;
			justify-content: center;
			border-radius: 100rpx;
			height: 84rpx;
		}

		.btn_buy {
			width: 30%;
			display: flex;
			background-color: #x-theme-color;
			color: #fff;
			align-items: center;
			height: 100%;
			justify-content: center;
			border-radius: 100rpx;
			height: 84rpx;
			margin-left: 20rpx;
		}

		.sale-out,
		.presale-product {
			background: #EEEDEC;
			color: #BDBBBA;
			height: calc(100% - 20rpx);
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 20rpx;
			border-radius: 10rpx;
		}
	}

	.alert {
		padding: 20rpx;
		background-color: #fff;
		width: 100%;

		.alert_title {
			display: flex;
			justify-content: space-between;

			.goods_info {
				display: flex;

				.goods_img {
					width: 160rpx;
					height: 160rpx;
					border-radius: 10rpx;
					overflow: hidden;
					margin-right: 20rpx;

					&>image {
						width: 100%;
					}
				}

				.desc {
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					align-items: flex-start;

					.unit {
						font-family: PingFang-SC;
						margin-top: 10rpx;
						font-weight: 400;
						color: #999;
						font-size: 28rpx;
					}
				}
			}

			.alert_right {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				justify-content: space-between;

				.ic_close {
					width: 48rpx;
					height: 46rpx;
				}
			}
		}

		.btn_sub {
			// width: 610rpx;
			height: 72rpx;
			// background-color: #f56c6c;
			// color: #fff;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 40rpx auto 0;
		}
	}

	.u-notice-bar {
		z-index: 999;
		background-color: #a7a1a1 !important;
		opacity: 0.7 !important;
		position: fixed;
		top: 50;
		left: 10;
		width: 100%;
	}

	.input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 90rpx;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);

		.picker {
			display: flex;
			align-items: center;

			&>image {
				width: 36rpx;
				height: 36rpx;
				font-size: 28rpx;
				margin-left: 10rpx;
			}

			.placeholder {
				font-size: 28rpx;
				color: #707070;
			}
		}

		&>input {
			width: 440rpx;
			font-size: 28rpx;
			text-align: right;
		}
	}
	.introduce{
		width: 100%;
		padding:0 20rpx 120rpx;
		
		
		video{
			width: 100%;
		}
	}
	.sku{
		margin: 50rpx auto;
		.sku_btn{
			display: inline-block;
			padding: 10rpx 20rpx;
			border: 2rpx solid #ededed;
			margin-right: 20rpx;
			margin-bottom:20rpx;
			font-size: 24rpx;
		}
	}
	
</style>